package com.haibo.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.stereotype.Component;

/**
 * aop切换数据源
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class DataSourceAspect {

    private final ConfigurableBeanFactory beanFactory;

    private final DataSourceProperties dataSourceProperties;

    @Around("@annotation(annotation) || @within(annotation)")
    public Object around(ProceedingJoinPoint point, DataSource annotation) throws Throwable {
        // 解析注解值
        String dataSourceKey = beanFactory.resolveEmbeddedValue(annotation.value());
        if (dataSourceProperties.getDynamicSouces() == null || !dataSourceProperties.getDynamicSouces().containsKey(dataSourceKey)) {
            log.warn("@DataSource[{} -> {}]对应的数据源不存在, 将使用默认数据源", annotation.value(), dataSourceKey);
        }

        // 切换数据源
        DataSourceSwitcher.setDataSourceKey(dataSourceKey);
        try {
            log.info(Thread.currentThread()+"-数据源当前启用：{}",dataSourceKey);
            return point.proceed();
        } finally {
            DataSourceSwitcher.clearDataSourceKey();
            log.info(Thread.currentThread()+"-数据源清理后：{}",DataSourceSwitcher.getDataSourceKey());
        }
    }

}
